import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/component/base_components.dart';
import 'package:flutter_niandaxue/config/font.dart';
import 'package:flutter_niandaxue/config/index.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'course/course_question_page.dart';

class CoursePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => new _CoursePageState();
}
// 课程视图页面
class _CoursePageState extends State<CoursePage> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin{
  List courseList = [];
  TabController _tabController ;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    // 初始化 Tab 导航视图监听
    this._tabController = new TabController(vsync:this, length: 2);
//    _controller.addListener((){});
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:  Colors.white,
      appBar: AppBar(
        title: Text(KString.courseTitle),
      ),
      body:Scaffold(
        appBar: AppBar(
          backgroundColor:  Colors.white,
          title: TabBar(
            indicatorSize: TabBarIndicatorSize.label,
            labelColor: Colors.blueAccent,
            unselectedLabelColor: Colors.black,
            indicatorColor: Colors.white,
            tabs: <Widget>[
              _getTab("自考"),
              _getTab("软考"),
//           new Tab(text: "收藏课程", icon: new Icon(Icons.favorite)),
            ],
            controller: this._tabController,
          ),
        ),
        body: TabBarView(
          controller: this._tabController,
          children: <Widget>[
            new CoursePageColumn(courseFlag:1),
            new CoursePageColumn(courseFlag:3),
          ],
        ),
      ),
    );
  }

  Tab _getTab(titleName){
    return new Tab(
      child: Row(
        children: <Widget>[
          Icon(Icons.book, size: 20,),
          Text(titleName,
            textAlign: TextAlign.left,
            style: TextStyle(
              fontSize: 20,
            ),
          ),
        ],
      ),
    );
  }
  @override
  void dispose() {
    this._tabController.dispose();
    super.dispose();
  }
}

/*
 * 课程列组件, 适配全部课程、收藏课程
 *  2020-02-18
 */
class CoursePageColumn extends StatefulWidget{

  final int courseFlag;
  CoursePageColumn({this.courseFlag});

  @override
  State<StatefulWidget> createState() => new _CoursePageColumnState(courseFlag:this.courseFlag);
}
/*
 * 课程列组件, 适配全部课程、收藏课程
 *  2020-02-18
 */
class _CoursePageColumnState extends State<CoursePageColumn> with AutomaticKeepAliveClientMixin{

  int courseFlag;
  _CoursePageColumnState({this.courseFlag});

  List courseList = [];
  int currentPage = 1;
  int totalPage = 1;
  int total = 0;

  var _icons;
  String loadMoreText = "没有更多数据";
  TextStyle loadMoreTextStyle = new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);

  @override
  void initState() {
    super.initState();
    initLoadData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: RefreshIndicator(
          child: Center(
            child: this.buildContent(context),
          ),
          onRefresh: _onRefresh,
        ),
    );
  }
  Future<Null> _onRefresh() async{
    initLoadData();
    return;
  }

  initLoadData() async{
    this.courseList.clear();
    this.currentPage = 0;
    this._getList();
  }

  Widget buildContent(BuildContext context) {
    // 1 数据为空时, 显示空视图
    if (this.courseList.length == 0) {
      return NothingListView();
    }
    // 2 构建视图列表
    ListView listView = ListView.builder(
      itemBuilder: this.buildTitleContent,
      itemCount: this.courseList.length,
    );
    return listView;
  }

  Widget buildTitleContent(context, index) {
    _icons = Icons.book;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 2.0),
      margin: const EdgeInsets.only(bottom: 2.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 2.0,
            offset: Offset(3.0, 2.0),
          ),
        ],
      ),
      child: _listTitle(index),
    );
  }

  Widget _listTitle(index){
    var courseJson = this.courseList[index];
    Course course = Course.fromJson(courseJson);
    return  ListTile(
      leading: Image.network(course.logoUrl,
        height: 150,
      ),
      title: Text(
        course.name,
        overflow: TextOverflow.ellipsis,
        style:  KFont.courseTitleStyle,
      ),
      subtitle:Text(course.subTitle,
        style: KFont.courseSubTitleStyle,
      ),
      trailing:
      Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(
            builder:(context){
              return new CourseQuestionPage(course:course, isAddStudyFlag: false);
            }
        ));
      },
    );
  }

  void lastPrompt(){
    if(this.currentPage == this.totalPage){
      this.loadMoreText = "没有更多数据";
    }
  }
  void _getList() async {
    var formPage = {'page':{'current':1,'size':15},'courseFlag':courseFlag};
    request_post_json('course/listPage', formData:formPage).then((val){
      var data = json.decode(val.toString());
      Page page = Page.fromJson(data['data']);
      setState(() {
        List rows = page.records;
        this.totalPage = page.pages;
        this.total = page.total;
        this.currentPage = page.current;
        this.lastPrompt();
        this.courseList.addAll(rows) ;
      });
    });
  }
  @override
  bool get wantKeepAlive => true;

}